package com.classtest.DemoExpend.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.classtest.DemoExpend.bean.DbGoods;
import com.classtest.DemoExpend.dao.DbGoodsDao;
import com.classtest.DemoExpend.service.DbGoodsService;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

@Service
public class DbGoodsServiceImpl extends ServiceImpl<DbGoodsDao, DbGoods> implements DbGoodsService {
    @Autowired
    DbGoodsDao dbGoodsDao;

    @Override
    public List<DbGoods> getGoodsCount(String json) {
        return dbGoodsDao.getGoodsCount(JSONObject.parseObject(json,DbGoods.class));
    }

    @Override
    public void deleteGoods(String id) {
        dbGoodsDao.deleteGoods(id);
    }

    @Override
    public void insertEXImage(String json) {
        dbGoodsDao.insertExImage(JSONObject.parseObject(json,DbGoods.class));
    }

    @Override
    public void uploadImage(String json, MultipartFile multipartFile) throws Exception {
        DbGoods dbGoods = JSONObject.parseObject(json,DbGoods.class);

        String path = dbGoods.getImageR();
        String imageName = dbGoods.getId();
        dbGoods.setMainImage(imageName+".png");
        dbGoodsDao.uploadImage(dbGoods);
        uploadFile(multipartFile.getBytes(),path+"\\",imageName+".png");
    }

    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath +"/"+ fileName);
        out.write(file);
        out.flush();
        out.close();
    }
}
